package com.example.project.webControlleer;

import com.example.project.dao.UserDAO;
import com.example.project.pojo.User;
import com.mysql.cj.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("web")
public class WebUserInfoUpdateController {
    @GetMapping("userinfoupdate")
    public String userinfoupdate(HttpServletRequest request) {
        HttpSession session = request.getSession();
        request.setAttribute("user", session.getAttribute("user"));
        return "/web/userinfoupdate";
    }

    @RequestMapping("userInfoUpdateCheck")
    public String userInfoUpdateCheck(User user, MultipartFile face, HttpServletRequest request) {
        UserDAO userDAO = new UserDAO();
        String filepath = request.getServletContext().getRealPath("/static/uploadimages");

        if (face.getSize() > 0) {
            String orginalfilename = face.getOriginalFilename();
            int index = orginalfilename.lastIndexOf(".");
            String fileext = orginalfilename.substring(index + 1);
            String filename = UUID.randomUUID() + "." + fileext;
            user.setUserFace(filename);
            try {
                face.transferTo(new File(filepath + "/" + filename));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            user.setUserFace("1.jpg");
        }
        userDAO.UserUpdate(user);
        return "redirect:/web/login";
    }
}
